<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/static/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/layuiadmin/style/admin.css" media="all">
</head>
<style>
    .shu .layui-form-radio {
        display: block !important;
    }

    .layui-table tbody tr:hover {
        background: #fff;
    }

    input[disabled] {
        cursor: not-allowed;
        background-color: #eee;
    }

    .layui-form-radioed.layui-radio-disbaled>i {
        color: #5FB878 !important;
    }
</style>
<body>
<div class="layui-form" lay-filter="layuiadmin-app-form-list" id="layuiadmin-app-form-list" style="padding: 20px 30px 0 0;">
    <input type="hidden" name="id" value="{$find.id}">
    <input type="hidden" name="shop" value="{$find.shop}">
    <fieldset class="layui-elem-field layui-field-title">
        <legend style="margin-left: 47px;">优惠券基础信息</legend>
    </fieldset>
    <div class="layui-form-item">
        <label class="layui-form-label">优惠券名称: </label>
        <div class="layui-input-inline">
            <input type="text" name="name" value="{$find.name}" lay-verify="required" placeholder="最多支持10个字" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">发放总量: </label>
        <div class="layui-input-inline" style="width: 110px;">
            <input type="text" name="total" value="{$find.total ? $find.total : 0}" lay-verify="required|number" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">张,0为不限</div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">优惠形式: </label>
        <div class="layui-input-block shu" style="padding-top: 1px;">
            <input type="radio" name="form" value="0" title="指定金额" lay-filter="xingshi" {if condition="$find.form == '0'"}checked="checked"{elseif condition="!$find"/}checked="checked"{/if} {if condition="$find"}disabled="disabled"{/if}>
            <div class="layui-input-block zhi" style="margin-left: 30px;">
                <span>面值：</span><input type="number" name="zhi" value="{$find.discount}" lay-verify="che0" class="layui-input" style="display: inline-block;width: 80px;" {if condition="$find"}disabled{/if}>
            </div>
            <input type="radio" name="form" value="1" title="折扣" lay-filter="xingshi" {if condition="$find.form == '1'"}checked="checked"{/if} {if condition="$find"}disabled="disabled"{/if}>
            <div class="layui-input-block layui-hide zhe" style="margin-left: 30px;">
                <input type="number" name="zhe" value="{$find.discount}" onkeyup="num(this)" lay-verify="che1" class="layui-input" style="display: inline-block;width: 80px;" {if condition="$find"}disabled{/if}><span> 折</span>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用门槛: </label>
        <div class="layui-input-block shu" style="padding-top: 1px;">
            <input type="radio" name="doorsill" value="0" title="不限制" {if condition="$find.doorsill == '0'"}checked="checked"{elseif condition="!$find"/}checked="checked"{/if} {if condition="$find"}disabled="disabled"{/if}>
            <input type="radio" name="doorsill" value="1" title="满 <input type='number' name='man' value='{$find.full}' lay-verify='che2' class='layui-input' style='display: inline-block;width: 80px;' {if condition='$find'}disabled{/if}> 元可用" {if condition="$find.doorsill == '1'"}checked="checked"{/if} {if condition="$find"}disabled="disabled"{/if}>
        </div>
    </div>
    <fieldset class="layui-elem-field layui-field-title">
        <legend style="margin-left: 47px;">基本规则</legend>
    </fieldset>
    <div class="layui-form-item">
        <label class="layui-form-label">每人限领: </label>
        <div class="layui-input-inline">
            <select name="limit" {if condition="$find"}disabled{/if}>
                <option value="0" {eq name="find.limit" value="0"}selected{/eq}>不限张数</option>
                <option value="1" {eq name="find.limit" value="1"}selected{/eq}>1张</option>
                <option value="2" {eq name="find.limit" value="2"}selected{/eq}>2张</option>
                <option value="3" {eq name="find.limit" value="3"}selected{/eq}>3张</option>
                <option value="4" {eq name="find.limit" value="4"}selected{/eq}>4张</option>
                <option value="5" {eq name="find.limit" value="5"}selected{/eq}>5张</option>
                <option value="6" {eq name="find.limit" value="6"}selected{/eq}>6张</option>
                <option value="7" {eq name="find.limit" value="7"}selected{/eq}>7张</option>
                <option value="8" {eq name="find.limit" value="8"}selected{/eq}>8张</option>
                <option value="9" {eq name="find.limit" value="9"}selected{/eq}>9张</option>
                <option value="10" {eq name="find.limit" value="10"}selected{/eq}>10张</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">有效期限: </label>
        <div class="layui-input-block shu" style="padding-top: 1px;">
            <input type="radio" name="term" value="0" title="指定开始结束时间" lay-filter="qixian" {if condition="$find.term == '0'"}checked="checked"{elseif condition="!$find"/}checked="checked"{/if} {if condition="$find"}disabled="disabled"{/if}>
            <div class="layui-input-block zhiding" style="margin-left: 30px;">
                <div><span>开始时间：</span><input type="text" name="start" value="{$find.start}" lay-verify='che3' class="layui-input" id="test1" autocomplete="off" style="display: inline-block;width: 150px;" {if condition="$find"}disabled{/if}></div>
                <div><span>结束时间：</span><input type="text" name="end" value="{$find.end}" lay-verify='che4' class="layui-input" id="test2" autocomplete="off" style="display: inline-block;width: 150px; margin-top: 10px;" {if condition="$find"}disabled{/if}></div>
            </div>
            <input type="radio" name="term" value="1" title="领券当时起 <input type='number' name='tian' value='{$find.valid}' lay-verify='che2' class='layui-input' style='display: inline-block;width: 80px;' {if condition='$find'}disabled{/if}> 天内有效" lay-filter="qixian" {if condition="$find.term == '1'"}checked="checked"{/if} {if condition="$find"}disabled="disabled"{/if}>
        </div>
    </div>
    {if condition="$find eq ''"}
    <div class="layui-form-item">
        <label class="layui-form-label">适用范围: </label>
        <div class="layui-input-block">
            <input type="radio" name="apply" value="0" title="全店通用" lay-filter="apply" {if condition="$find.apply == '0'"}checked="checked"{elseif condition="!$find"/}checked="checked"{/if}>
            <input type="radio" name="apply" value="1" title="指定商品" lay-filter="apply" {if condition="$find.apply == '1'"}checked="checked"{/if}>
        </div>
        <div class="layui-input-block layui-hide tables" style="width: 400px;">
            <table class="layui-table" lay-skin="line" lay-verify='che5'>
                <colgroup>
                    <col width="340">
                    <col width="60">
                </colgroup>
                <thead>
                <tr>
                    <th>商品名称</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {volist name='shop' id='vo'}
                <tr>
                    <td>{$vo.name}</td>
                    <td>
                        <a href="javascript:;" class="delete" data-id="{$vo.id}" style="color: #337ab7;">删除</a>
                    </td>
                </tr>
                {/volist}
                </tbody>
            </table>
            <div>
                <a href="javascript:;" style="color: #337ab7;" id="demo" ts-selected="{$find.shop}">+添加商品</a>
            </div>
        </div>
    </div>
    {/if}
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">使用说明: </label>
        <div class="layui-input-block" style="width: 350px;">
            <textarea class="layui-textarea" name="explain">{$find.explain}</textarea>
        </div>
    </div>
    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="layuiadmin-app-form-submit" id="layuiadmin-app-form-submit" value="提交">
        <input type="button" lay-submit lay-filter="layuiadmin-app-form-edit" id="layuiadmin-app-form-edit" value="修改">
    </div>
    <script type="text/html" id="time">
        {{ formatDateTime(d.time) }}
    </script>
</div>
<script src="/static/layuiadmin/layui/layui.js"></script>
<script type="text/javascript" src="/static/js/jquery-3.1.1.min.js"></script>
<script>
    layui.config({
        base: '/static/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'laydate', 'form', 'tableSelect'], function(){
        var $ = layui.$,
                form = layui.form,
                laydate = layui.laydate,
                tableSelect = layui.tableSelect;

        form.verify({
            che0: function(value, item){ //value：表单的值、item：表单的DOM对象
                var che = $(item).parent().prevAll('input[type=radio]:first:checked').val();
                if (che === '0'){
                    if (!value){
                        return '必填项不能为空';
                    }
                }
            },
            che1: function(value, item){ //value：表单的值、item：表单的DOM对象
                var che = $(item).parent().prevAll('input[type=radio]:first:checked').val();
                if (che === '1'){
                    if (!value){
                        return '必填项不能为空';
                    }else if (value >= 10 || value <= 0){
                        return '折扣必须为0~10之间';
                    }
                }
            },
            che2: function(value, item){ //value：表单的值、item：表单的DOM对象
                var che = $(item).parent().parent().prevAll('input[type=radio]:first:checked').val();
                if (che === '1'){
                    if (!value){
                        return '必填项不能为空';
                    }
                }
            },
            che3: function(value, item){
                var che = $(item).parent().parent().prevAll('input[type=radio]:first:checked').val();
                if (che === '0'){
                    if (!value){
                        return '必填项不能为空';
                    }
                }
            },
            che4: function(value, item){
                var che = $(item).parent().parent().prevAll('input[type=radio]:first:checked').val();
                if (che === '0'){
                    var start = $("input[name=start]").val();
                    if (!value){
                        return '必填项不能为空';
                    }else if (value <= start){
                        return '结束时间必须大于开始时间';
                    }
                }
            },
            che5: function (value, item) {
                var che = $(item).parent().prev().find('input[type=radio]:checked').val();
                if (che === '1'){
                    var length = $(".tables tbody tr").length;
                    if (length == '0'){
                        return '至少要选择一件商品';
                    }
                }
            }
        });

        tableSelect.render({
            elem: '#demo',	//定义输入框input对象
            checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
            searchKey: 'name',	//搜索输入框的name值 默认keyword
            searchPlaceholder: '搜索商品名称',	//搜索输入框的提示文字 默认关键词搜索
            table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                url: "{:url('Product/product')}",
                method: 'post',
                cols: [[
                    {type: 'checkbox'},
                    {field: 'name', title: '商品名称', width: 400},
                    {field: 'stock', title: '库存', width: 100},
                    {field: 'volume', title: '销量', width: 100},
                    {field: 'time', title: '添加时间', width: 200, templet: "#time"}
                ]]
            },
            done: function (elem, data) {
                //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
                //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
                var field = data.data;
                var id = [];
                $(".tables tbody").html('');
                for (var i = 0; i < field.length; i++){
                    $(".tables tbody").append('<tr><td>'+ field[i].name +'</td><td><a href="javascript:;" class="delete" data-id="'+ field[i].id +'" style="color: #337ab7;">删除</a></td></tr>');
                    id.push(field[i].id);
                }
                id.join(',');
                $("input[name=shop]").val(id);
            }
        });

        //删除
        $(".tables").on('click', '.delete', function () {
            //删除元素
            $(this).parents('tr').remove();
            //重新修改商品id
            var id = [];
            $(".tables tbody a").each(function(){
                var data_id = $(this).data('id');
                id.push(data_id);
            });
            id.join(',');
            $("input[name=shop]").val(id);
            $("#demo").attr('ts-selected', id);
        });

        laydate.render({
            elem: '#test1' //指定元素
            ,type: 'datetime'
        });

        laydate.render({
            elem: '#test2' //指定元素
            ,type: 'datetime'
        });

        var xingshi = "{$find.form}";
        if (xingshi == 0){
            $(".zhi").removeClass('layui-hide');
            $(".zhe").addClass('layui-hide');
        }else{
            $(".zhi").addClass('layui-hide');
            $(".zhe").removeClass('layui-hide');
        }

        //监听优惠方式
        form.on('radio(xingshi)', function(data){
            if (data.value == 0){
                $(".zhi").removeClass('layui-hide');
                $(".zhe").addClass('layui-hide');
            }else{
                $(".zhi").addClass('layui-hide');
                $(".zhe").removeClass('layui-hide');
            }
        });

        var term = "{$find.term}";
        if (term == 0){
            $(".zhiding").removeClass('layui-hide');
        }else{
            $(".zhiding").addClass('layui-hide');
        }

        //监听期限
        form.on('radio(qixian)', function(data){
            if (data.value == 0){
                $(".zhiding").removeClass('layui-hide');
            }else{
                $(".zhiding").addClass('layui-hide');
            }
        });

        var apply = "{$find.apply}";
        if (apply == 0){
            $(".tables").addClass('layui-hide');
        }else{
            $(".tables").removeClass('layui-hide');
        }

        //监听适用
        form.on('radio(apply)', function(data){
            if (data.value == 0){
                $(".tables").addClass('layui-hide');
            }else{
                $(".tables").removeClass('layui-hide');
            }
        });

        //添加
        form.on('submit(layuiadmin-app-form-submit)', function(data){
            var field = data.field;
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            $.post("{:url('Product/coupon_add')}", {field:field}, function(e){
                if (e == 1){
                    layer.msg('添加成功', {icon: 1});
                    setTimeout(function () {
                        parent.layui.table.reload('demo'); //重载表格
                        parent.layer.close(index); //再执行关闭
                    }, 500)
                }else{
                    layer.msg('添加失败', {icon: 2});
                }
            })
        });

        //修改
        form.on('submit(layuiadmin-app-form-edit)', function(data){
            var field = data.field;
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            $.post("{:url('Product/coupon_edit')}", {field:field}, function(e){
                if (e == 1){
                    layer.msg('修改成功', {icon: 1});
                    setTimeout(function () {
                        parent.layui.table.reload('demo'); //重载表格
                        parent.layer.close(index); //再执行关闭
                    }, 500)
                }else{
                    layer.msg('修改失败', {icon: 2});
                }
            })
        });
    });

    function num(obj){
        obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
        obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
        obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
        obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
    }


    //php时间戳用js转换为yyyy-mm-dd
    function formatDateTime(timeStamp) {
        var date = new Date();
        date.setTime(timeStamp * 1000);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    }
</script>
</body>
</html>